<template>
  <a-tree-select
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    :tree-data="treeData"
    :filterTreeNode="filterTreeNode"
    :value="_value"
    placeholder="请选择"
    showSearch
    style="width: 100%"
    allowClear
    @change="handleChange"
  >
  </a-tree-select>
</template>

<script lang="ts">
import { Vue, Component, Model } from "vue-property-decorator";
import { TreeSelect } from "ant-design-vue";

@Component({
  name: "CDepartment",
  components: {
    ATreeSelect: TreeSelect
  }
})
export default class CDepartment extends Vue {
  @Model("input") value!: any;
  private dataSource: any[] = [];

  private get _value() {
    const _return = this.value;
    return _return ? _return : undefined;
  }

  private created() {
    this.getDeptTree();
  }

  private async getDeptTree() {
    const res = await this.$api.DeptAllTreeSelect();
    if (res && res.code === 200) {
      this.dataSource = res.data;
    }
  }

  private handleChange(value: string) {
    this.$emit("input", value);
  }

  private filterTreeNode(inputValue: string, treeNode: any) {
    return treeNode.data.props.title.indexOf(inputValue) > -1;
  }

  private dataReorganization(data: any) {
    if (data && data.length) {
      for (const item of data) {
        item.title = item.label;
        item.value = item.id;
        item.key = item.id;
        if (item.children && item.children.length) {
          this.dataReorganization(item.children);
        }
      }
    }
  }

  private get treeData() {
    const _return: any[] = [...this.dataSource];
    this.dataReorganization(_return);
    return _return;
  }
}
</script>
